package com.imooc.mmall.common;

import com.imooc.mmall.exception.UserException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import com.imooc.common.ServerResponse;

import javax.servlet.http.HttpServletRequest;

/**
 * springweb全局异常处理
 */
@Slf4j
@ControllerAdvice
@ResponseBody
public class WebExceptionHandle {

    /**
     * 400 - Bad Request
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public ServerResponse handleHttpMessageNotReadableException(HttpMessageNotReadableException e) {
        log.error("参数解析失败！error="+e.getMessage(), e);
        return ServerResponse.createByErrorMessage("参数解析失败！"+e.getMessage());
    }

    /**
     * 405 - Method Not Allowed
     */
    @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public ServerResponse handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
        log.error("不支持当前请求方法！error="+e.getMessage(), e);
        return ServerResponse.createByErrorMessage("不支持当前请求方法！"+e.getMessage());
    }

    /**
     * 415 - Unsupported Media Type
     */
    @ResponseStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE)
    @ExceptionHandler(HttpMediaTypeNotSupportedException.class)
    public ServerResponse handleHttpMediaTypeNotSupportedException(Exception e) {
        log.error("不支持当前媒体类型！error="+e.getMessage(), e);
        return ServerResponse.createByErrorMessage("不支持当前媒体类型！"+e.getMessage());
    }

    /**
     * 500 - Internal Server Error
     */
    //@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(Exception.class)
    public ServerResponse handleException(Exception e, HttpServletRequest request) {
        //判断是否是自定义异常
        if (e instanceof UserException){
            return ServerResponse.createByErrorMessage("用户相关异常！"+e.getMessage());
        }
        log.error("服务运行异常！error="+e.getMessage(), e);
        return ServerResponse.createByErrorMessage("服务运行异常！error="+e.getMessage());
    }
}
